﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace EasyEncryption
{
    class Encryptor
    {
        SymmetricAlgorithm encryptionAlgorithm;

        public Encryptor(SymmetricAlgorithm sa)
        {
            encryptionAlgorithm = sa;
        }

        public byte[] EncryptTextToMemory(string data, string key, string IV)
        {
            return EncryptTextToMemory(data, new ASCIIEncoding().GetBytes(key), new ASCIIEncoding().GetBytes(IV));
        }

        public byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
        {
            try
            {
                byte[] ret;
                byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

                using (MemoryStream mStream = new MemoryStream())
                {

                    using (CryptoStream cStream = new CryptoStream(mStream,
                        encryptionAlgorithm.CreateEncryptor(Key, IV),
                        CryptoStreamMode.Write))
                    {
                        cStream.Write(toEncrypt, 0, toEncrypt.Length);
                        cStream.FlushFinalBlock();

                        ret = mStream.ToArray();

                        cStream.Close();
                        mStream.Close();
                    }
                    return ret;
                }
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }

        }

        public byte[] DecryptString(string Data, string Key, string IV)
        {
            return DecryptString(Data, new ASCIIEncoding().GetBytes(Key), new ASCIIEncoding().GetBytes(IV));
        }

        public byte[] DecryptString(string Data, byte[] Key, byte[] IV)
        {

            
                byte[] ret;
                byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

                using (MemoryStream mStream = new MemoryStream())
                {

                    using (CryptoStream cStream = new CryptoStream(mStream,
                        encryptionAlgorithm.CreateDecryptor(Key, IV),
                        CryptoStreamMode.Write))
                    {
                        cStream.Write(toEncrypt, 0, toEncrypt.Length);
                        cStream.FlushFinalBlock();

                        ret = mStream.ToArray();

                        cStream.Close();
                        mStream.Close();
                    }
                    return ret;
                }
            }
     


        }
    }
